package com.wise.service.cms.content.code;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.RandomUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.wise.framework.basic.EnumUtil;
import com.wise.framework.consts.Consts;
import com.wise.framework.exception.Excep;
import com.wise.framework.validation.Precondition;
import com.wise.model.content.GetVerificationCodeResult;
import com.wise.model.content.utils.SetCode2Cache;
import com.wise.model.content.utils.UseCodeType;
import com.wise.summer.v1.cms.content.verificationcode.GetVerificationCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import static com.wise.model.content.ContentErrMsgs.Err_100100110001;
import static com.wise.model.content.utils.VerificationCodeType.PIC;

/**
 * @author yubo
 */
@Slf4j
@Service
@SummerService
public class GetVerificationCodeService implements SummerServiceBean<GetVerificationCode> {
    public static final String BASE_STRING = "0123456789";
    public static final int LENGTH = 6;
    public static final String NAME = "name";
    public static final String CODE = "code";
    public static final String LIFE_MINUTE = "lifeMinute";

//    @Autowired
//    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

//    @Value("${app.rabbitmq.sms.exchange}")
//    private String smsExchangeKey;
//
//    @Value("${app.smstemplate.register}")
//    private String register;
//
//    @Value("${app.smstemplate.login}")
//    private String login;
//
//    @Value("${app.smstemplate.bind-mobile}")
//    private String bindMobile;
//
//    @Value("${app.smstemplate.preorder-verify}")
//    private String preorderVerify;
//
//    @Value("${app.internationalization.smstemplate.register}")
//    private String internationalizationRegister;
//
//    @Value("${app.internationalization.smstemplate.login}")
//    private String internationalizationLogin;
//
//    @Value("${app.internationalization.smstemplate.bind-mobile}")
//    private String internationalizationBindMobile;
//
//    @Value("${app.internationalization.smstemplate.preorder-verify}")
//    private String internationalizationPreorderVerify;

//    private static final String CHINA_AREA_CODE = "86";

    /**
     * 图形
     */
    @Autowired
    private DefaultKaptcha producer;

    @Override
    public void sum(GetVerificationCode summer) {

        Precondition.checkNotNull(summer.getType(), Err_100100110001);
        Precondition.checkState(EnumUtil.exists(UseCodeType.class, summer.getUseType()), Err_100100110001);

        GetVerificationCodeResult result = new GetVerificationCodeResult();

        String randomId = RandomUtil.simpleUUID();
        result.setVerifyKey(randomId);

        String key = Consts.REDIS_VERIFY_KEY_KEY + summer.getUseType() + randomId;
        if (EnumUtil.is(PIC, summer.getType())) {
            //获取图形验证码
            result = resultVerificationCodeByPicture(result, key);
        }
//        else {
//            Precondition.checkState(StringUtils.isNotBlank(summer.getAccount()), Err_000500000001);
//            result = resultVerificationCodeBySend(summer, result, key);
//        }

        summer.setSummerResult(result);
    }

    /**
     * 生成图片
     */
    private GetVerificationCodeResult resultVerificationCodeByPicture(GetVerificationCodeResult result, String key) {
        // 生成文字验证码
        String code = producer.createText();
        System.out.println(code);
        // 生成图片验证码
        ByteArrayOutputStream outputStream;
        BufferedImage image = producer.createImage(code);
        outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);

            // 对字节数组Base64编码
            String str = Base64.encode(outputStream.toByteArray());
            str = str.replaceAll("[\\s*\t\n\r]", "");
            result.setImg("data:image/png;base64," + str);

            //redis
            SetCode2Cache.s(key, code);
            log.info("pic verify code:" + key + " " + code);
        } catch (IOException e) {
            throw Excep.ae(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
        return result;
    }

    /**
     * 发送短信
     */
//    private GetVerificationCodeResult resultVerificationCodeBySend(GetVerificationCode summer, GetVerificationCodeResult result, String key) {
//
//        UseCodeType useCodeType = EnumUtil.valueOf(UseCodeType.class, summer.getUseType(), Excep.le(Err_000500000003));
//
//        Boolean checkSetSmssended = CheckSetSmsSended.s(summer.getAccount(), useCodeType.value());
//        Precondition.checkState(checkSetSmssended, Err_000500000002);
//
//        //生成验证码
//        String code = RandomUtil.randomString(BASE_STRING, LENGTH);
//
//        String smsContent = JSON.toJSONString(Kv.inst(CODE, code).kv(LIFE_MINUTE, "5"));
//
//        SmsModel smsModel = new SmsModel();
//        smsModel.setMobile(summer.getAccount());
//        if(StringUtils.isNotBlank(summer.getAreaCode())&&!Objects.equals(summer.getAreaCode(),CHINA_AREA_CODE)){
//            smsModel.setMobile(summer.getAreaCode()+summer.getAccount());
//        }
//        if (StringUtils.isBlank(summer.getAreaCode())|| Objects.equals(summer.getAreaCode(),CHINA_AREA_CODE)){
//            if (EnumUtil.is(UseCodeType.register,summer.getUseType())){
//                smsModel.setTemplateCode(register);
//            }else if (EnumUtil.is(UseCodeType.login,summer.getUseType())){
//                smsModel.setTemplateCode(login);
//            }else if (EnumUtil.is(UseCodeType.bind_mobile,summer.getUseType())){
//                smsModel.setTemplateCode(bindMobile);
//            }else if (EnumUtil.is(UseCodeType.preorder_verify,summer.getUseType())){
//                smsModel.setTemplateCode(preorderVerify);
//            }
//        }else{
//            if (EnumUtil.is(UseCodeType.register,summer.getUseType())){
//                smsModel.setTemplateCode(internationalizationRegister);
//            }else if (EnumUtil.is(UseCodeType.login,summer.getUseType())){
//                smsModel.setTemplateCode(internationalizationLogin);
//            }else if (EnumUtil.is(UseCodeType.bind_mobile,summer.getUseType())){
//                smsModel.setTemplateCode(internationalizationBindMobile);
//            }else if (EnumUtil.is(UseCodeType.preorder_verify,summer.getUseType())){
//                smsModel.setTemplateCode(internationalizationPreorderVerify);
//            }
//        }
//        smsModel.setTemplateParam(smsContent);
//
//        rabbitTemplate.convertAndSend(smsExchangeKey, null, JSON.toJSONString(smsModel));
//
//        SetCode2Cache.s(key, code+summer.getAccount());
//        log.info("sms verify code:"+key+" "+code+" mobile:"+summer.getAccount());
//        String isexist = redisTemplate.opsForValue().get(key);
//        log.info("=============isexist:{}================",isexist);
//        result.setMsg(true);
//
//        return result;
//    }
}
